<template>
    <div class="m-mobile-layer-container"
         :class="options.class"
         :ref="options.id"
         :style="dialogStyle"
    >
        <div v-if="noComponent">{{ i18n('noAvailable', '暂无弹窗模板') }}</div>
    </div>
</template>

<script>
import {createApp} from 'vue'

export default {
    name: "mobileLayer",
    props: {
        options: {}
    },
    data() {
        return {
            vm: null,
            noComponent: false
        }
    },
    computed: {
        dialogStyle() {
            let {zIndex} = this.options;
            if (zIndex || zIndex === 0) {
                return {zIndex}
            }
            return {zIndex: 1000}
        }
    },
    created() {
        this.$nextTick(() => {
            this.createVM()
        })
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "allLang", key);
        },
        /**
         * 获取被打开组件的属性数据.
         */
        getOptions(data, curVm, dialogOptions) {
            let {dialogClose} = this;
            let obj = {
                dialogClose,
                parentVm: () => curVm,
                dialogOptions: dialogOptions,
                ...data
            }
            return obj;
        },
        /**
         *
         * */
        setComponents(vm, components) {
            for (let key in components) {
                vm.component(key, components[key])
            }
        },
        /**
         * 创建被打开组件的示例.
         */
        createVM() {
            let {id, component, data, globalApp, curVm, dialogOptions,components} = this.options;
            if (!component) {
                this.noComponent = true;
                return;
            }
            dialogOptions = dialogOptions || {};
            let options = this.getOptions(data, curVm, dialogOptions);
            let _root = this.$refs[`${id}`];
            let _vm = createApp(component, options);
            _vm.config.globalProperties = globalApp.config.globalProperties;
            this.setComponents(_vm, components)
            _vm.mount(_root);
        },
        /**
         *
         * @param obj
         */
        dialogClose(obj) {
            let {destroy} = this.options;
            obj && destroy && destroy(obj)
            if (this.vm) {
                this.vm.unmount();
                this.vm = null;
            }
        },
        setVm(vm) {
            this.vm = vm;
        }
    }
}
</script>

<style scoped>
.m-mobile-layer-container {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    background-color: #fff;
}
</style>
